package vtt.android.cartoon_video.fragments;

import java.util.ArrayList;
import java.util.List;

import necvn.android.youtube_helper.YoutubeApiHelper;
import necvn.android.youtube_helper.YoutubeApiHelper.OnYoutubeResponseListener;
import vtt.android.cartoon_video.R;
import vtt.android.cartoon_video.adapters.BaseListAdapter;
import vtt.android.cartoon_video.dialogs.DialogManager;
import vtt.android.cartoon_video.entities.CommonHashMap;
import vtt.android.cartoon_video.entities.YoutubeItem;
import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;

import com.google.api.services.youtube.model.SearchResult;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.twotoasters.jazzylistview.JazzyHelper;
import com.twotoasters.jazzylistview.JazzyListView;

/**
 * A placeholder fragment containing a simple view.
 */
public class BaseMainFragment extends BaseFragment {

    protected static final String ARG_SECTION_NUMBER = "SECTION_NUMBER";
    protected static final String ARG_SEARCH_KEY = "SEARCH_KEY";
    protected static final String KEY_TRANSITION_EFFECT = "transition_effect";
    
    // search key
    private String mSearchKey;
    
    protected OnItemSelectedListener listener;
    protected ParseTask parseTask;
    protected JazzyListView mListview;
    protected BaseListAdapter mAdapter;

    // item list
    protected List<YoutubeItem> mItemList;
    // parent activity
    protected Activity mParentAct;

    protected int mCurrentTransitionEffect = JazzyHelper.STANDARD;
    protected View mProgressBar;
    protected ImageView mBgImage;
    
    private YoutubeApiHelper mYoutubeHelper;
    
    public static BaseMainFragment newInstance(int sectionNumber, String searchKey) {
        BaseMainFragment fragment = new BaseMainFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putString(ARG_SEARCH_KEY, searchKey);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mParentAct = activity;
        if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet BaseMainFragment.OnItemSelectedListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mItemList = new ArrayList<YoutubeItem>();
        mAdapter = new BaseListAdapter(mParentAct, mItemList);
        mYoutubeHelper = new YoutubeApiHelper(mParentAct, getString(R.string.youtube_api_key), getString(R.string.app_name));
        mYoutubeHelper.setNumOfVideoReturn(50);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        log.d("VTT>>> " + "onCreateView");

        View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);

        mBgImage = (ImageView) rootView.findViewById(R.id.img_bacground);
        mBgImage.setImageResource(CommonHashMap.getRandomBackgroundId());

        mListview = (JazzyListView) rootView.findViewById(R.id.listview_rss);
        mListview.setAdapter(mAdapter);
        mListview.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true, onScrollListener));
        mListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                YoutubeItem youtubeItem = (YoutubeItem) mAdapter.getItem(position);
                listener.onYoutubeItemSelected(youtubeItem.item.getId().getVideoId());
            }
        });

        if (savedInstanceState != null) {
            mCurrentTransitionEffect = savedInstanceState.getInt(KEY_TRANSITION_EFFECT, mCurrentTransitionEffect);
        }

        if(Build.VERSION.RELEASE.contains("4.4.4")){
            mCurrentTransitionEffect = JazzyHelper.STANDARD;
        }
        
        setupJazziness(mCurrentTransitionEffect);

        // Look up the AdView as a resource and load a request.
        /*AdView adView = (AdView) rootView.findViewById(R.id.adView);
        loadAdmob(adView);*/
        // init progress bar
        mProgressBar = rootView.findViewById(R.id.progressBar1);

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        mSearchKey = getArguments().getString(ARG_SEARCH_KEY);
        mYoutubeHelper.searchData(mSearchKey, new OnYoutubeResponseListener() {

            @Override
            public void onSuccess(List<SearchResult> itemList) {
                // TODO Auto-generated method stub
                mProgressBar.setVisibility(View.GONE);
                // reset list item
                mItemList.clear();
                if(itemList != null && itemList.size() > 0){
                    for (int i = 0; i < itemList.size(); i++) {
                        if (i % 7 == 0) {
                            YoutubeItem adItem = new YoutubeItem();
                            mItemList.add(adItem);
                        }
                        YoutubeItem youtubeItem = new YoutubeItem();
                        youtubeItem.item = itemList.get(i);
                        mItemList.add(youtubeItem);
                    }
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onSearchStart() {
                // show progress
                if (mProgressBar != null && !mProgressBar.isShown()) {
                    mProgressBar.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Exception e) {
                // TODO Auto-generated method stub
                mProgressBar.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        log.d("VTT>>> onOptionsItemSelected BaseMainFragment ");
        switch (item.getItemId()) {
        case R.id.action_refresh:

            if (!VttUtils.checkNetworkConnection(mParentAct)) {
                mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_INFOR,
                        getString(R.string.msg_title_notice), getString(R.string.msg_network_error), null);
                return true;
            }
            // show progress bar
            // mProgressBar.setVisibility(View.VISIBLE);
            // change background for listview
            mBgImage.setImageResource(CommonHashMap.getRandomBackgroundId());
            /*if(mParentAct instanceof MainActivity){
                ((MainActivity)mParentAct).changeBackground();
            }*/
            
            // reset list
            mItemList.clear();
            mAdapter.clear();
            mAdapter.notifyDataSetChanged();
            parseTask = null;
            
            // TODO refresh
            
            break;

        case R.id.action_menu_rate_app:
            VttGA.sendEvent(mParentAct, "BaseMainFragment", "Gop Y", "", 0);
            VttUtils.openGooglePlayMarket(mParentAct, mParentAct.getPackageName());
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_TRANSITION_EFFECT, mCurrentTransitionEffect);
    }

    private void setupJazziness(int effect) {
        mCurrentTransitionEffect = effect;
        mListview.setTransitionEffect(mCurrentTransitionEffect);
    }

    /**
     * update list data
     * 
     * @param rssUrl
     */
    public void updateListContent(String rssUrl) {
        if(getActivity() == null){
            return;
        }
        
        log.d("VTT>>> " + "updateListContent " + rssUrl);
        if (parseTask == null) {
            // show progress
            if(mProgressBar != null && !mProgressBar.isShown()){
                mProgressBar.setVisibility(View.VISIBLE);
            }
            parseTask = new ParseTask();
            try {
                parseTask.execute(rssUrl);
            } catch (Exception e) {
                VttGA.sendException(mParentAct, e.getMessage() + " ; url " + rssUrl);
            }
        }
    }

    /**
     * update list item
     * @param result
     */
    protected void updateListData(List<YoutubeItem> result){
        if(result != null && result.size() > 0){
            for (int i = 0; i < result.size(); i++) {
                if (i % 7 == 0) {
                    YoutubeItem adItem = new YoutubeItem();
                    mItemList.add(adItem);
                }
                mItemList.add(result.get(i));
            }
        }
    };

    // add event scroll listener
    OnScrollListener onScrollListener = new OnScrollListener() {
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            // Log.v("TEST", "VTT>>> onScroll firstVisibleItem " + firstVisibleItem + "; visibleItemCount "
            // + visibleItemCount + "; totalItemCount " + totalItemCount);
            if ((firstVisibleItem + visibleItemCount + 1) >= totalItemCount) {
                // TODO check next page
                
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            
        }
    };

    private class ParseTask extends AsyncTask<String, Void, ArrayList<YoutubeItem>> {
        @Override
        protected void onPreExecute() {

            // TODO text image cache size
            /*
             * int sumbyte = 0; MemoryCache memoryCache = ImageLoader.getInstance().getMemoryCache(); for (String key :
             * memoryCache.keys()) { Bitmap bitmap = memoryCache.get(key); log.d("VTT>>> bitmap.getByteCount() " +
             * bitmap.getByteCount()); sumbyte += bitmap.getByteCount(); } log.d("VTT>>> sumbyte " + sumbyte);
             */

            // check network
            if (!VttUtils.checkNetworkConnection(mParentAct)) {
                mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_INFOR, getString(R.string.msg_title_notice),
                        getString(R.string.msg_network_error), null);
            }
            super.onPreExecute();
        }

        @Override
        protected ArrayList<YoutubeItem> doInBackground(String... params) {
            log.d("VTT>>> " + "doInBackground");
            ArrayList<YoutubeItem> list = new ArrayList<YoutubeItem>();
            String searchKeyword = params[0];
            
            
            return list;
        }

        @Override
        protected void onPostExecute(final ArrayList<YoutubeItem> result) {
            log.d("VTT>>> " + "onPostExecute");
            try {
                mParentAct.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        
                        updateListData(result);

                        mAdapter.notifyDataSetChanged();
                        parseTask = null;
                    }
                });
            } catch (Exception e) {
                // VttGA.sendException(mParentAct,"GA onPostExecute error : " + e.getMessage());
                e.printStackTrace();
            }
            mProgressBar.setVisibility(View.GONE);
        }
    }
    
    public interface OnItemSelectedListener {
        public void onYoutubeItemSelected(String link);
    }
}